package handler

import (
	"fmt"
	"gmfs/core/storage"
	"gmfs/core/web/ink"
	"io"
)

/**
 * 文件下载
 * http://localhost:1323/download
 */
func Download(ctx *ink.Context) {
	var id = ctx.Param("id")
	var name = ctx.Input()["name"]

	//查询 gridfs
	ii, gf, err := storage.FindInfoById(Connection, id)
	if err != nil || !allowReq(ctx) {
		ctx.Body = []byte("not found")
		ctx.End()
		return
	} else {
		defer gf.Close()

		//存在文件
		if ii != nil {
			if name == "" {
				name = ii.GetFid()
			}
			output := ctx.Response.Header()
			output.Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s%s", name, ii.GetFileSuffix()))
			output.Set("Content-Type", ii.GetContentType())
			io.Copy(ctx.Response, gf)
		}
	}

	ctx.IsSend = true
}

/**
 * 读取硬盘文件下载
 * http://localhost:1323/download
 */
//func Download(ctx *ink.Context) {
//	ctx.Download("c://gopic//scape.gif")
//}
